package com.firmail.thread;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * @author asdf
 * @Description ThreadLocal ,
 * 将请求HttpServletRequest，HttpServletResponse放入ThreadLocal中，方便获取
 * @date 2018年1月12日 上午10:55:26
 */
public class MockThreadLocal {
    private static ThreadLocal<HttpServletRequest> threadLocalRequest = new ThreadLocal<>();
    //
    private static ThreadLocal<HttpServletResponse> threadLocalResponse = new ThreadLocal<>();
    //
    private static ThreadLocal<Map<String, Object>> threadLocalMap = new ThreadLocal<>();
    private static final String LOCAL_USER_KEY = "local_user_Key";

    public static void setThreadLocalRequest(HttpServletRequest request) {
        Map<String, Object> map = threadLocalMap.get();
        if (map == null) {
            threadLocalMap.set(new HashMap<>());
        }
        threadLocalRequest.set(request);
    }

    public static void setThreadLocalResponse(HttpServletResponse response) {
        threadLocalResponse.set(response);
    }

    public static HttpServletRequest getRequest() {
        return threadLocalRequest.get();
    }

    public static HttpServletResponse getResponse() {
        return threadLocalResponse.get();
    }

    public static Map<String, Object> getThreadLocalMap() {
        Map<String, Object> map = threadLocalMap.get();
        if (map == null) {
            threadLocalMap.set(new HashMap<>());
        }
        return threadLocalMap.get();
    }

    public static Object getThreadLocalMap(String key) {
        return getThreadLocalMap().get(key);
    }

    public static String getString(String key) {
        return (String) getThreadLocalMap(key);
    }

    public static String getUserId() {
        return (String) getThreadLocalMap(LOCAL_USER_KEY);
    }

    public static void setUserId(String userId) {
        getThreadLocalMap().put(LOCAL_USER_KEY, userId);
    }


    public static void clear() {
        threadLocalRequest.remove();
        threadLocalResponse.remove();
        threadLocalMap.remove();
    }

}
